package com.qfedu.fmmall.service.job;

import com.github.wxpay.sdk.WXPay;
import com.qfedu.fmmall.dao.OrderItemMapper;
import com.qfedu.fmmall.dao.OrdersMapper;
import com.qfedu.fmmall.dao.ProductSkuMapper;
import com.qfedu.fmmall.entity.OrderItem;
import com.qfedu.fmmall.entity.Orders;
import com.qfedu.fmmall.entity.ProductSku;
import com.qfedu.fmmall.service.OrdersService;
import com.qfedu.fmmall.service.config.MyPayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : yanBin
 * @date :2021/12/21 17:58
 */
@Component
public class OrderTimeOutCheckJob {
    private static final Logger log = LoggerFactory.getLogger(OrderTimeOutCheckJob.class);

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrdersService ordersService;

    private WXPay wxPay = new WXPay(new MyPayConfig());

    @Scheduled(cron = "0/60 * * * * ?")
    public void checkAndCloseOrder() {
        try { //1.查询超过30分钟订单状态是否已经为支付订单
            System.out.println("dsrw--------------------");
            Example example = new Example(Orders.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status", "1");
            Date date = new Date(System.currentTimeMillis() - 30 * 60 * 1000);
            criteria.andLessThan("createTime", date);
            List<Orders> orders = ordersMapper.selectByExample(example);

            //2.0访问微信平台接口，确认当前订单是否是支付状态
            for (Orders order : orders) {
                HashMap<String, String> map = new HashMap<>();
                map.put("out_trade_no", order.getOrderId());   //订单id
                //访问微信服务平台接口，查询订单接口状态
                Map<String, String> resp = wxPay.orderQuery(map);

                //2.1如果已经支付，则修改订单状态为“待发货”status=2
                if ("SUCCESS".equals(resp.get("trade_state"))) {
                    Orders orders1 = new Orders();
                    orders1.setOrderId(order.getOrderId());
                    orders1.setStatus("2");
                    ordersMapper.updateByPrimaryKeySelective(orders1);
                //2.2如果确实未支付，则取消订单
                } else if ("NOTPAY".equals(resp.get("trade_state"))) {
                    //2.3向微信平台发送请求关闭订单状态
                    Map<String, String> map2 = wxPay.closeOrder(map);

                    //2.4修改当前订单：status=6 已关闭 close_type=1超时未支付,2.5还原库存
                    ordersService.closeOrder(order.getOrderId());
                }
            }
        } catch (Exception e) {
          log.error(e.getMessage());
        }
    }

}
